<template>
  <div class="calendar-view">
    <!-- 日历头部控制栏 -->
    <div class="calendar-header">
      <div class="calendar-navigation">
        <button class="nav-btn" @click="previousPeriod">
          <svg width="16" height="16" viewBox="0 0 24 24" fill="none">
            <path d="M15 18L9 12L15 6" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
          </svg>
        </button>
        
        <div class="current-period">
          <h2>{{ currentPeriodText }}</h2>
        </div>
        
        <button class="nav-btn" @click="nextPeriod">
          <svg width="16" height="16" viewBox="0 0 24 24" fill="none">
            <path d="M9 18L15 12L9 6" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
          </svg>
        </button>
      </div>
      
      <div class="view-controls">
        <button 
          class="view-btn" 
          :class="{ active: viewMode === 'month' }"
          @click="setViewMode('month')"
        >
          月
        </button>
        <button 
          class="view-btn" 
          :class="{ active: viewMode === 'week' }"
          @click="setViewMode('week')"
        >
          周
        </button>
        <button 
          class="view-btn" 
          :class="{ active: viewMode === 'day' }"
          @click="setViewMode('day')"
        >
          日
        </button>
        <button class="today-btn" @click="goToToday">今天</button>
      </div>
    </div>
    
    <!-- 日历主体 -->
    <div class="calendar-body">
      <!-- 月视图 -->
      <div v-if="viewMode === 'month'" class="month-view">
        <div class="weekdays">
          <div v-for="day in weekdays" :key="day" class="weekday">{{ day }}</div>
        </div>
        <div class="month-grid">
          <div 
            v-for="date in monthDates" 
            :key="date.key"
            class="date-cell"
            :class="{
              'other-month': !date.isCurrentMonth,
              'today': date.isToday,
              'selected': date.isSelected
            }"
            @click="selectDate(date)"
          >
            <div class="date-number">{{ date.date }}</div>
            <div class="date-tasks">
              <div 
                v-for="task in getTasksForDate(date.fullDate)" 
                :key="task.id"
                class="task-item"
                :class="{ completed: task.completed }"
                :style="{ backgroundColor: getTaskListColor(task) + '20', borderLeft: '3px solid ' + getTaskListColor(task) }"
                @click.stop="editTask(task)"
              >
                <div class="task-checkbox">
                  <input 
                    type="checkbox" 
                    :checked="task.completed"
                    @click.stop
                    @change="toggleTaskCompleted(task.id, $event)"
                  >
                </div>
                <span class="task-title">{{ task.title }}</span>
              </div>
            </div>
          </div>
        </div>
      </div>
      
      <!-- 周视图 -->
      <div v-if="viewMode === 'week'" class="week-view">
        <div class="week-header">
          <div class="time-column"></div>
          <div 
            v-for="date in weekDates" 
            :key="date.key"
            class="day-header"
            :class="{ 'today': date.isToday }"
          >
            <div class="day-name">{{ date.dayName }}</div>
            <div class="day-number">{{ date.date }}</div>
          </div>
        </div>
        <div class="week-body">
          <div class="time-slots">
            <div v-for="hour in 24" :key="hour" class="time-slot">
              <div class="time-label">{{ formatHour(hour - 1) }}</div>
            </div>
          </div>
          <div class="week-days">
            <div 
              v-for="date in weekDates" 
              :key="date.key"
              class="day-column"
            >
              <div v-for="hour in 24" :key="hour" class="hour-slot">
                <div 
                  v-for="task in getTasksForDateAndHour(date.fullDate, hour - 1)" 
                  :key="task.id"
                  class="task-item"
                  :class="{ completed: task.completed }"
                  :style="{ backgroundColor: getTaskListColor(task) + '20', borderLeft: '3px solid ' + getTaskListColor(task) }"
                  @click="editTask(task)"
                >
                  <div class="task-checkbox">
                    <input 
                      type="checkbox" 
                      :checked="task.completed"
                      @click.stop
                      @change="toggleTaskCompleted(task.id, $event)"
                    >
                  </div>
                  <span class="task-title">{{ task.title }}</span>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
      
      <!-- 日视图 -->
      <div v-if="viewMode === 'day'" class="day-view">
        <div class="day-header">
          <h3>{{ selectedDate.toLocaleDateString('zh-CN', { weekday: 'long', year: 'numeric', month: 'long', day: 'numeric' }) }}</h3>
        </div>
        <div class="day-body">
          <div class="day-timeline">
            <div class="time-column">
              <div v-for="hour in 24" :key="hour" class="time-slot">
                <div class="time-label">{{ formatHour(hour - 1) }}</div>
              </div>
            </div>
            <div class="tasks-column">
              <div class="hour-grid">
                <div v-for="hour in 24" :key="hour" class="hour-line"></div>
              </div>
              <div class="tasks-container">
                <div 
                  v-for="(task, index) in getDayTasks(selectedDate)" 
                  :key="task.id"
                  class="task-block"
                  :class="{ 
                    completed: task.completed,
                    'default-task': !task.listId,
                    'list-task': task.listId
                  }"
                  :style="getTaskBlockStyle(task, index)"
                  @click="editTask(task)"
                >
                  <div class="task-checkbox">
                    <input 
                      type="checkbox" 
                      :checked="task.completed"
                      @click.stop
                      @change="toggleTaskCompleted(task.id, $event)"
                    >
                  </div>
                  <div class="task-content">
                    <div class="task-title">{{ task.title }}</div>
                    <div class="task-time">{{ formatTaskTimeRange(task) }}</div>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
    
    <!-- 任务编辑弹窗 -->
    <div v-if="showTaskEdit" class="task-edit-overlay" @click="closeTaskEdit">
      <div class="task-edit-modal" @click.stop>
        <div class="modal-header">
          <h3>编辑任务</h3>
          <button class="close-btn" @click="closeTaskEdit">
            <svg width="16" height="16" viewBox="0 0 24 24" fill="none">
              <path d="M18 6L6 18M6 6L18 18" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
            </svg>
          </button>
        </div>
        <div class="modal-body" v-if="editingTask">
          <div class="form-group">
            <label>任务标题</label>
            <input
              v-model="editingTask.title"
              type="text"
              placeholder="输入任务标题"
              class="form-input"
            />
          </div>

          <div class="form-row">
            <div class="form-group">
              <label>优先级</label>
              <select v-model="editingTask.priority" class="form-select">
                <option value="none">无</option>
                <option value="low">低</option>
                <option value="medium">中</option>
                <option value="high">高</option>
              </select>
            </div>

            <div class="form-group">
              <label>番茄钟数量</label>
              <input
                v-model.number="editingTask.pomodoroRequired"
                type="number"
                min="0"
                max="20"
                class="form-input"
              />
            </div>
          </div>

          <div class="form-row">
            <div class="form-group">
              <label>开始时间</label>
              <input 
                :value="formatDateTimeForInput(editingTask.startTime)"
                @input="updateTaskStartTime($event.target.value)"
                type="datetime-local" 
                class="form-input"
              />
            </div>

            <div class="form-group">
              <label>到期时间</label>
              <input 
                :value="formatDateTimeForInput(editingTask.dueDate)"
                @input="updateTaskDueDate($event.target.value)"
                type="datetime-local" 
                class="form-input"
              />
            </div>
          </div>

          <div class="form-row">
            <div class="form-group">
              <label>循环设置</label>
              <select v-model="editingTask.recurrence" class="form-select">
                <option value="none">不循环</option>
                <option value="daily">每日</option>
                <option value="weekly">每周</option>
                <option value="monthly">每月</option>
              </select>
            </div>
          </div>

          <div class="form-group">
            <label>所属清单</label>
            <select v-model="editingTask.listId" class="form-select">
              <option value="">无清单</option>
              <option
                v-for="list in state.lists"
                :key="list.id"
                :value="list.id"
              >
                {{ list.name }}
              </option>
            </select>
          </div>

          <div class="form-group">
            <label>备注</label>
            <textarea
              v-model="editingTask.notes"
              placeholder="添加备注信息"
              rows="3"
              class="form-textarea"
            ></textarea>
          </div>
        </div>
        <div class="modal-footer">
          <button class="btn btn-secondary" @click="closeTaskEdit">取消</button>
          <button class="btn btn-primary" @click="saveTaskEdit">保存</button>
        </div>
      </div>
    </div>
    
    <!-- 重复任务时间错误提示模态框 -->
    <div v-if="showRepeatTaskTimeError" class="modal-overlay">
      <div class="repeat-task-error-modal" @click.stop>
        <div class="modal-header">
          <div class="modal-title">
            <svg width="20" height="20" viewBox="0 0 24 24" fill="none" class="warning-icon">
              <path d="M10.29 3.86L1.82 18a2 2 0 0 0 1.71 3h16.94a2 2 0 0 0 1.71-3L13.71 3.86a2 2 0 0 0-3.42 0z" stroke="#f59e0b" stroke-width="2" fill="none"/>
              <line x1="12" y1="9" x2="12" y2="13" stroke="#f59e0b" stroke-width="2"/>
              <circle cx="12" cy="17" r="1" fill="#f59e0b"/>
            </svg>
            重复任务时间提醒
          </div>
          <button class="close-btn" @click="closeRepeatTaskTimeError">
            <svg width="16" height="16" viewBox="0 0 16 16" fill="none">
              <path d="M12 4L4 12M4 4L12 12" stroke="currentColor" stroke-width="2" stroke-linecap="round"/>
            </svg>
          </button>
        </div>
        <div class="modal-content">
          <div class="error-info">
            <p class="error-message">
              不能在任务开始时间之前完成重复任务
            </p>
            <div class="task-info">
              <p><strong>任务名称：</strong>{{ repeatTaskTimeErrorData.taskTitle }}</p>
              <p><strong>任务开始时间：</strong>{{ repeatTaskTimeErrorData.startDate }}</p>
              <p><strong>当前时间：</strong>{{ repeatTaskTimeErrorData.currentDate }}</p>
            </div>
            <p class="error-submessage">
              请等到任务开始时间后再标记为完成，或者修改任务的开始时间。
            </p>
          </div>
        </div>
        <div class="modal-actions">
          <button class="confirm-btn" @click="closeRepeatTaskTimeError">
            我知道了
          </button>
        </div>
      </div>
    </div>

    <!-- 重复任务完成状态错误提示模态框 -->
    <div v-if="showRepeatTaskCompleteError" class="modal-overlay">
      <div class="repeat-task-error-modal" @click.stop>
        <div class="modal-header">
          <div class="modal-title">
            <svg width="20" height="20" viewBox="0 0 24 24" fill="none" class="error-icon">
              <circle cx="12" cy="12" r="10" stroke="#ef4444" stroke-width="2" fill="none"/>
              <line x1="15" y1="9" x2="9" y2="15" stroke="#ef4444" stroke-width="2"/>
              <line x1="9" y1="9" x2="15" y2="15" stroke="#ef4444" stroke-width="2"/>
            </svg>
            重复任务状态提醒
          </div>
          <button class="close-btn" @click="closeRepeatTaskCompleteError">
            <svg width="16" height="16" viewBox="0 0 16 16" fill="none">
              <path d="M12 4L4 12M4 4L12 12" stroke="currentColor" stroke-width="2" stroke-linecap="round"/>
            </svg>
          </button>
        </div>
        <div class="modal-content">
          <div class="error-info">
            <p class="error-message">
              {{ repeatTaskCompleteErrorData.message }}
            </p>
            <div class="task-info">
              <p><strong>任务名称：</strong>{{ repeatTaskCompleteErrorData.taskTitle }}</p>
            </div>
            <p class="error-submessage">
              重复任务一旦完成就会自动创建下一个实例，因此不能取消完成状态。如需修改，请直接编辑新创建的任务实例。
            </p>
          </div>
        </div>
        <div class="modal-actions">
          <button class="confirm-btn" @click="closeRepeatTaskCompleteError">
            我知道了
          </button>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, onUnmounted } from 'vue'
import { useTodoStore } from '@/stores/todoStore'

const { state, updateTask, toggleTaskCompleted: storeToggleTaskCompleted, currentTasks } = useTodoStore()

// 包装toggleTaskCompleted方法以处理复选框状态
const toggleTaskCompleted = (taskId, event) => {
  const result = storeToggleTaskCompleted(taskId)
  
  // 如果store方法返回false，说明操作被阻止，需要恢复复选框状态
  if (result === false && event && event.target) {
    // 恢复复选框的原始状态
    event.target.checked = !event.target.checked
  }
  
  return result
}

// 响应式数据
const viewMode = ref('month') // 'month', 'week', 'day'
const selectedDate = ref(new Date())
const showTaskEdit = ref(false)
const editingTask = ref(null)

// 重复任务时间错误提示模态框
const showRepeatTaskTimeError = ref(false)
const repeatTaskTimeErrorData = ref({})

// 重复任务完成状态错误提示模态框
const showRepeatTaskCompleteError = ref(false)
const repeatTaskCompleteErrorData = ref({})

// 星期名称
const weekdays = ['日', '一', '二', '三', '四', '五', '六']

// 处理重复任务时间错误事件
const handleRepeatTaskTimeError = (event) => {
  repeatTaskTimeErrorData.value = event.detail
  showRepeatTaskTimeError.value = true
}

// 关闭重复任务时间错误模态框
const closeRepeatTaskTimeError = () => {
  showRepeatTaskTimeError.value = false
  repeatTaskTimeErrorData.value = {}
}

// 处理重复任务完成状态错误事件
const handleRepeatTaskCompleteError = (event) => {
  repeatTaskCompleteErrorData.value = event.detail
  showRepeatTaskCompleteError.value = true
}

// 关闭重复任务完成状态错误模态框
const closeRepeatTaskCompleteError = () => {
  showRepeatTaskCompleteError.value = false
  repeatTaskCompleteErrorData.value = {}
}

// 计算属性
const currentPeriodText = computed(() => {
  const date = selectedDate.value
  if (viewMode.value === 'month') {
    return `${date.getFullYear()}年${date.getMonth() + 1}月`
  } else if (viewMode.value === 'week') {
    const weekStart = getWeekStart(date)
    const weekEnd = new Date(weekStart)
    weekEnd.setDate(weekEnd.getDate() + 6)
    return `${weekStart.getMonth() + 1}月${weekStart.getDate()}日 - ${weekEnd.getMonth() + 1}月${weekEnd.getDate()}日`
  } else {
    return date.toLocaleDateString('zh-CN', { year: 'numeric', month: 'long', day: 'numeric' })
  }
})

// 月视图日期数据
const monthDates = computed(() => {
  const year = selectedDate.value.getFullYear()
  const month = selectedDate.value.getMonth()
  const firstDay = new Date(year, month, 1)
  const lastDay = new Date(year, month + 1, 0)
  const startDate = new Date(firstDay)
  startDate.setDate(startDate.getDate() - firstDay.getDay())
  
  const dates = []
  const today = new Date()
  
  for (let i = 0; i < 42; i++) {
    const date = new Date(startDate)
    date.setDate(startDate.getDate() + i)
    
    dates.push({
      key: `${date.getFullYear()}-${date.getMonth()}-${date.getDate()}`,
      date: date.getDate(),
      fullDate: new Date(date),
      isCurrentMonth: date.getMonth() === month,
      isToday: date.toDateString() === today.toDateString(),
      isSelected: date.toDateString() === selectedDate.value.toDateString()
    })
  }
  
  return dates
})

// 周视图日期数据
const weekDates = computed(() => {
  const weekStart = getWeekStart(selectedDate.value)
  const dates = []
  const today = new Date()
  
  for (let i = 0; i < 7; i++) {
    const date = new Date(weekStart)
    date.setDate(weekStart.getDate() + i)
    
    dates.push({
      key: `${date.getFullYear()}-${date.getMonth()}-${date.getDate()}`,
      date: date.getDate(),
      fullDate: new Date(date),
      dayName: weekdays[date.getDay()],
      isToday: date.toDateString() === today.toDateString()
    })
  }
  
  return dates
})

// 方法
const setViewMode = (mode) => {
  viewMode.value = mode
}

const previousPeriod = () => {
  const date = new Date(selectedDate.value)
  if (viewMode.value === 'month') {
    date.setMonth(date.getMonth() - 1)
  } else if (viewMode.value === 'week') {
    date.setDate(date.getDate() - 7)
  } else {
    date.setDate(date.getDate() - 1)
  }
  selectedDate.value = date
}

const nextPeriod = () => {
  const date = new Date(selectedDate.value)
  if (viewMode.value === 'month') {
    date.setMonth(date.getMonth() + 1)
  } else if (viewMode.value === 'week') {
    date.setDate(date.getDate() + 7)
  } else {
    date.setDate(date.getDate() + 1)
  }
  selectedDate.value = date
}

const goToToday = () => {
  const today = new Date()
  const currentSelected = selectedDate.value
  
  // 设置选中日期为今天
  selectedDate.value = new Date(today)
  
  // 添加视觉反馈 - 短暂高亮今天按钮
  const todayBtn = document.querySelector('.today-btn')
  if (todayBtn) {
    todayBtn.classList.add('clicked')
    setTimeout(() => {
      todayBtn.classList.remove('clicked')
    }, 200)
  }
  
  // 为不同视图模式添加视觉反馈动画
  setTimeout(() => {
    if (viewMode.value === 'month') {
      // 月视图：高亮今天的日期格子
      const todayCells = document.querySelectorAll('.date-cell.today')
      todayCells.forEach(cell => {
        cell.classList.add('highlight')
        setTimeout(() => {
          cell.classList.remove('highlight')
        }, 1000)
      })
    } else if (viewMode.value === 'week') {
      // 周视图：高亮今天的列头
      const todayHeaders = document.querySelectorAll('.day-header.today')
      todayHeaders.forEach(header => {
        header.style.animation = 'todayHighlight 1s ease-in-out'
        setTimeout(() => {
          header.style.animation = ''
        }, 1000)
      })
    } else if (viewMode.value === 'day') {
       // 日视图：高亮整个日期标题
       const dayHeader = document.querySelector('.day-header h3')
       if (dayHeader) {
         dayHeader.style.animation = 'todayHighlight 1s ease-in-out'
         setTimeout(() => {
           dayHeader.style.animation = ''
         }, 1000)
       }
     }
     
     // 滚动到今天的位置（如果需要）
     scrollToToday()
   }, 100)
  
  // 根据不同视图模式提供额外的用户反馈
  if (viewMode.value === 'month') {
    // 在月视图中，如果当前月份不是今天所在的月份，会自动切换到今天所在的月份
    const currentMonth = currentSelected.getMonth()
    const todayMonth = today.getMonth()
    const currentYear = currentSelected.getFullYear()
    const todayYear = today.getFullYear()
    
    if (currentMonth !== todayMonth || currentYear !== todayYear) {
      // 月份发生了变化，给用户一个提示
      console.log(`已跳转到${today.getFullYear()}年${today.getMonth() + 1}月`)
    }
  } else if (viewMode.value === 'week') {
    // 在周视图中，确保今天在当前周内
    const currentWeekStart = getWeekStart(currentSelected)
    const todayWeekStart = getWeekStart(today)
    
    if (currentWeekStart.getTime() !== todayWeekStart.getTime()) {
      // 周发生了变化
      console.log('已跳转到本周')
    }
  } else if (viewMode.value === 'day') {
    // 在日视图中，直接显示今天的详细信息
    console.log('已切换到今天的日视图')
  }
}

const selectDate = (dateObj) => {
  selectedDate.value = dateObj.fullDate
}

const getWeekStart = (date) => {
  const start = new Date(date)
  start.setDate(date.getDate() - date.getDay())
  return start
}

const getTasksForDate = (date) => {
  const dateStr = date.toDateString()
  // 使用currentTasks而不是state.tasks，这样会应用左侧导航菜单的筛选条件
  return currentTasks.value.filter(task => {
    // 检查任务是否有截止日期或开始时间在当天
    // 使用逻辑或操作符，避免重复返回同一个任务
    const hasStartTimeOnDate = task.startTime && new Date(task.startTime).toDateString() === dateStr
    const hasDueDateOnDate = task.dueDate && new Date(task.dueDate).toDateString() === dateStr
    
    return hasStartTimeOnDate || hasDueDateOnDate
  })
}

const getTasksForDateAndHour = (date, hour) => {
  const tasks = getTasksForDate(date)
  return tasks.filter(task => {
    try {
      // 优先使用开始时间
      if (task.startTime) {
        const taskHour = new Date(task.startTime).getHours()
        return taskHour === hour
      }
      // 如果没有开始时间但有截止时间，使用截止时间
      else if (task.dueDate) {
        const dueHour = new Date(task.dueDate).getHours()
        return dueHour === hour
      }
      // 如果都没有，默认显示在9点
      else {
        return hour === 9
      }
    } catch (error) {
      console.warn('处理任务时间失败:', error)
      return hour === 9 // 出错时默认显示在9点
    }
  })
}

const formatHour = (hour) => {
  return `${hour.toString().padStart(2, '0')}:00`
}

const formatTaskTime = (task) => {
  if (!task.startTime && !task.dueDate) return ''
  
  try {
    let timeStr = ''
    
    if (task.startTime) {
      const start = new Date(task.startTime)
      timeStr = `${start.getHours().toString().padStart(2, '0')}:${start.getMinutes().toString().padStart(2, '0')}`
    }
    
    if (task.dueDate) {
      const due = new Date(task.dueDate)
      const dueTimeStr = `${due.getHours().toString().padStart(2, '0')}:${due.getMinutes().toString().padStart(2, '0')}`
      
      if (timeStr) {
        timeStr += ` - ${dueTimeStr}`
      } else {
        timeStr = `截止 ${dueTimeStr}`
      }
    }
    
    return timeStr
  } catch (error) {
    console.warn('格式化任务时间失败:', error)
    return ''
  }
}

// 获取当天的所有任务
const getDayTasks = (date) => {
  const dateStr = date.toDateString()
  return currentTasks.value.filter(task => {
    const hasStartTimeOnDate = task.startTime && new Date(task.startTime).toDateString() === dateStr
    const hasDueDateOnDate = task.dueDate && new Date(task.dueDate).toDateString() === dateStr
    return hasStartTimeOnDate || hasDueDateOnDate
  }).sort((a, b) => {
    // 按开始时间排序，如果没有开始时间则按到期时间排序
    const aTime = a.startTime ? new Date(a.startTime) : (a.dueDate ? new Date(a.dueDate) : new Date())
    const bTime = b.startTime ? new Date(b.startTime) : (b.dueDate ? new Date(b.dueDate) : new Date())
    return aTime - bTime
  })
}

// 计算任务块的样式
const getTaskBlockStyle = (task, index) => {
  const style = {}
  
  // 计算任务的时间位置和高度
  let startHour = 9 // 默认开始时间
  let endHour = 10 // 默认结束时间
  let duration = 1 // 默认持续1小时
  
  if (task.startTime && task.dueDate) {
    // 有开始时间和结束时间
    const start = new Date(task.startTime)
    const end = new Date(task.dueDate)
    startHour = start.getHours() + start.getMinutes() / 60
    endHour = end.getHours() + end.getMinutes() / 60
    duration = endHour - startHour
    
    // 确保最小高度
    if (duration < 0.5) {
      duration = 0.5
      endHour = startHour + duration
    }
  } else if (task.startTime) {
    // 只有开始时间
    const start = new Date(task.startTime)
    startHour = start.getHours() + start.getMinutes() / 60
    duration = 1 // 默认1小时
    endHour = startHour + duration
  } else if (task.dueDate) {
    // 只有到期时间
    const due = new Date(task.dueDate)
    endHour = due.getHours() + due.getMinutes() / 60
    duration = 1 // 默认1小时
    startHour = endHour - duration
  }
  
  // 计算位置和大小
  const hourHeight = 60 // 每小时的像素高度
  const top = startHour * hourHeight
  const height = duration * hourHeight
  
  // 计算横向位置（处理重叠任务）
  const tasksAtSameTime = getDayTasks(new Date(task.startTime || task.dueDate || new Date()))
    .filter(t => {
      const tStart = t.startTime ? new Date(t.startTime) : (t.dueDate ? new Date(t.dueDate) : new Date())
      const tEnd = t.dueDate ? new Date(t.dueDate) : (t.startTime ? new Date(new Date(t.startTime).getTime() + 60*60*1000) : new Date())
      const currentStart = task.startTime ? new Date(task.startTime) : (task.dueDate ? new Date(task.dueDate) : new Date())
      const currentEnd = task.dueDate ? new Date(task.dueDate) : (task.startTime ? new Date(new Date(task.startTime).getTime() + 60*60*1000) : new Date())
      
      // 检查时间是否重叠
      return (tStart < currentEnd && tEnd > currentStart)
    })
  
  const taskIndex = tasksAtSameTime.findIndex(t => t.id === task.id)
  const totalOverlapping = tasksAtSameTime.length
  
  const taskWidth = totalOverlapping > 1 ? `${100 / totalOverlapping}%` : '100%'
  const leftOffset = totalOverlapping > 1 ? `${(taskIndex * 100) / totalOverlapping}%` : '0%'
  
  style.position = 'absolute'
  style.top = `${top}px`
  style.height = `${Math.max(height, 30)}px` // 最小高度30px
  style.width = taskWidth
  style.left = leftOffset
  style.zIndex = 10 + index
  
  // 设置背景色
  const color = getTaskListColor(task)
  if (task.listId) {
    // 清单任务：使用清单颜色
    style.backgroundColor = color + '40' // 40% 透明度
    style.borderLeft = `4px solid ${color}`
  } else {
    // 默认任务：使用灰色
    style.backgroundColor = '#6b728040'
    style.borderLeft = '4px solid #6b7280'
  }
  
  return style
}

// 格式化任务时间范围
const formatTaskTimeRange = (task) => {
  if (!task.startTime && !task.dueDate) return ''
  
  try {
    if (task.startTime && task.dueDate) {
      const start = new Date(task.startTime)
      const end = new Date(task.dueDate)
      const startStr = `${start.getHours().toString().padStart(2, '0')}:${start.getMinutes().toString().padStart(2, '0')}`
      const endStr = `${end.getHours().toString().padStart(2, '0')}:${end.getMinutes().toString().padStart(2, '0')}`
      return `${startStr} - ${endStr}`
    } else if (task.startTime) {
      const start = new Date(task.startTime)
      return `${start.getHours().toString().padStart(2, '0')}:${start.getMinutes().toString().padStart(2, '0')}`
    } else if (task.dueDate) {
      const due = new Date(task.dueDate)
      return `截止 ${due.getHours().toString().padStart(2, '0')}:${due.getMinutes().toString().padStart(2, '0')}`
    }
    return ''
  } catch (error) {
    console.warn('格式化任务时间范围失败:', error)
    return ''
  }
}

const editTask = (task) => {
  editingTask.value = { 
    ...task,
    pomodoroRequired: task.pomodoroRequired || 0,
    recurrence: task.recurrence || 'none',
    listId: task.listId || '',
    priority: task.priority || 'none',
    // 确保时间字段正确初始化
    startTime: task.startTime || null,
    dueDate: task.dueDate || null,
    notes: task.notes || ''
  }
  showTaskEdit.value = true
}

const closeTaskEdit = () => {
  showTaskEdit.value = false
  editingTask.value = null
}

// 获取任务所属清单的颜色
const getTaskListColor = (task) => {
  if (!task.listId) {
    return '#6b7280'; // 默认灰色，用于无清单的任务
  }
  
  const list = state.lists.find(list => list.id === task.listId);
  return list ? list.color : '#6b7280';
};

const saveTaskEdit = () => {
  if (editingTask.value) {
    try {
      // 验证必填字段
      if (!editingTask.value.title || !editingTask.value.title.trim()) {
        console.warn('任务标题不能为空')
        return
      }
      
      // 验证时间逻辑：只有当开始时间和到期时间都存在且不为空时才验证
      if (editingTask.value.startTime && editingTask.value.dueDate && 
          editingTask.value.startTime.trim() !== '' && editingTask.value.dueDate.trim() !== '') {
        const startTime = new Date(editingTask.value.startTime)
        const dueDate = new Date(editingTask.value.dueDate)
        if (startTime >= dueDate) {
          alert('到期时间不能早于或等于开始时间，请重新设置')
          return
        }
      }
      
      updateTask(editingTask.value.id, editingTask.value)
      closeTaskEdit()
    } catch (error) {
      console.error('保存任务失败:', error)
    }
  }
}

const formatDateTimeForInput = (dateTime) => {
  if (!dateTime) return ''
  try {
    const date = new Date(dateTime)
    // 转换为本地时间并格式化为YYYY-MM-DDTHH:mm格式
    const year = date.getFullYear()
    const month = String(date.getMonth() + 1).padStart(2, '0')
    const day = String(date.getDate()).padStart(2, '0')
    const hours = String(date.getHours()).padStart(2, '0')
    const minutes = String(date.getMinutes()).padStart(2, '0')
    return `${year}-${month}-${day}T${hours}:${minutes}`
  } catch (error) {
    console.warn('格式化时间失败:', error)
    return ''
  }
}

const updateTaskStartTime = (value) => {
  if (editingTask.value) {
    if (value) {
      try {
        editingTask.value.startTime = new Date(value).toISOString()
      } catch (error) {
        console.warn('更新开始时间失败:', error)
      }
    } else {
      editingTask.value.startTime = null
    }
  }
}

const updateTaskDueDate = (value) => {
  if (editingTask.value) {
    if (value) {
      try {
        editingTask.value.dueDate = new Date(value).toISOString()
      } catch (error) {
        console.warn('更新截止时间失败:', error)
      }
    } else {
      editingTask.value.dueDate = null
    }
  }
}

// 滚动到今天的位置
const scrollToToday = () => {
  if (viewMode.value === 'week') {
    // 在周视图中，滚动到当前时间附近
    const currentHour = new Date().getHours()
    const targetHour = Math.max(0, currentHour - 2) // 显示当前时间前2小时
    const weekBody = document.querySelector('.week-body')
    const timeSlot = document.querySelector(`.time-slot:nth-child(${targetHour + 1})`)
    if (weekBody && timeSlot) {
      // 计算目标位置相对于滚动容器的偏移
      const containerRect = weekBody.getBoundingClientRect()
      const targetRect = timeSlot.getBoundingClientRect()
      const scrollTop = weekBody.scrollTop + (targetRect.top - containerRect.top)
      
      // 平滑滚动到目标位置
      weekBody.scrollTo({
        top: scrollTop,
        behavior: 'smooth'
      })
    }
  } else if (viewMode.value === 'day') {
    // 在日视图中，滚动到当前时间附近
    const currentHour = new Date().getHours()
    const targetHour = Math.max(0, currentHour - 1) // 显示当前时间前1小时
    const dayBody = document.querySelector('.day-body')
    const timeSlot = document.querySelector(`.day-body .time-slot:nth-child(${targetHour + 1})`)
    if (dayBody && timeSlot) {
      // 计算目标位置相对于滚动容器的偏移
      const containerRect = dayBody.getBoundingClientRect()
      const targetRect = timeSlot.getBoundingClientRect()
      const scrollTop = dayBody.scrollTop + (targetRect.top - containerRect.top) - (dayBody.clientHeight / 3)
      
      // 平滑滚动到目标位置
      dayBody.scrollTo({
        top: Math.max(0, scrollTop),
        behavior: 'smooth'
      })
    }
  }
  // 月视图不需要滚动，因为整个月都在视图中
}

// 生命周期钩子
onMounted(() => {
  // 监听重复任务时间错误事件
  window.addEventListener('showRepeatTaskTimeError', handleRepeatTaskTimeError)
  // 监听重复任务完成状态错误事件
  window.addEventListener('showRepeatTaskCompleteError', handleRepeatTaskCompleteError)
})

onUnmounted(() => {
  // 移除事件监听器
  window.removeEventListener('showRepeatTaskTimeError', handleRepeatTaskTimeError)
  window.removeEventListener('showRepeatTaskCompleteError', handleRepeatTaskCompleteError)
})
</script>

<style lang="less" scoped>
.calendar-view {
  height: 100%;
  width: 100%;
  max-width: 100%;
  display: flex;
  flex-direction: column;
  background: var(--background-color);
  border-radius: 8px;
  overflow: hidden;
  box-sizing: border-box;
}

.calendar-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px 24px;
  border-bottom: 1px solid var(--border-color);
  background: var(--surface-color);
}

.calendar-navigation {
  display: flex;
  align-items: center;
  gap: 16px;
}

.nav-btn {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 32px;
  height: 32px;
  border: 1px solid var(--border-color);
  border-radius: 6px;
  background: var(--background-color);
  cursor: pointer;
  transition: all 0.2s;
  
  &:hover {
    background: var(--button-secondary-hover);
    border-color: var(--text-secondary);
  }
}

.current-period h2 {
  margin: 0;
  font-size: 18px;
  font-weight: 600;
  color: var(--text-primary);
}

.view-controls {
  display: flex;
  gap: 8px;
  align-items: center;
}

.view-btn {
  padding: 6px 12px;
  border: 1px solid var(--border-color);
  border-radius: 6px;
  background: var(--background-color);
  cursor: pointer;
  font-size: 14px;
  transition: all 0.2s;
  
  &:hover {
    background: var(--button-secondary-hover);
  }
  
  &.active {
    background: var(--primary-color);
    color: white;
    border-color: var(--primary-color);
  }
}

.today-btn {
  padding: 6px 12px;
  border: 1px solid var(--primary-color);
  border-radius: 6px;
  background: var(--background-color);
  color: var(--primary-color);
  cursor: pointer;
  font-size: 14px;
  transition: all 0.2s;
  
  &:hover {
    background: var(--primary-color);
    color: white;
  }
  
  &.clicked {
    background: var(--primary-color);
    color: white;
    transform: scale(0.95);
    box-shadow: 0 2px 8px rgba(var(--primary-color), 0.3);
  }
}

.calendar-body {
  flex: 1;
  overflow: auto;
  min-height: 0;
  width: 100%;
  max-width: 100%;
}

/* 月视图样式 */
.month-view {
  height: 100%;
  display: flex;
  flex-direction: column;
}

.weekdays {
  display: grid;
  grid-template-columns: repeat(7, 1fr);
  border-bottom: 1px solid var(--border-color);
  background: var(--surface-color);
}

.weekday {
  padding: 12px;
  text-align: center;
  font-weight: 600;
  color: var(--text-secondary);
  font-size: 14px;
}

.month-grid {
  display: grid;
  grid-template-columns: repeat(7, 1fr);
  grid-template-rows: repeat(6, 1fr);
  flex: 1;
  min-height: 0;
  width: 100%;
}

.date-cell {
  border-right: 1px solid var(--border-color);
  border-bottom: 1px solid var(--border-color);
  padding: 8px;
  cursor: pointer;
  transition: background-color 0.2s;
  min-height: 80px;
  max-height: 150px;
  overflow: hidden;
  box-sizing: border-box;
  
  &:hover {
    background: var(--button-secondary-hover);
  }
  
  &.other-month {
    color: var(--text-secondary);
    background: var(--surface-color);
  }
  
  &.today {
    background: rgba(var(--primary-color), 0.1);
    border: 2px solid var(--primary-color);
    position: relative;
    
    &::before {
      content: '';
      position: absolute;
      top: -2px;
      left: -2px;
      right: -2px;
      bottom: -2px;
      border: 2px solid var(--primary-color);
      border-radius: 4px;
      opacity: 0;
      animation: todayPulse 2s ease-in-out infinite;
      pointer-events: none; /* 确保伪元素不会阻止鼠标事件 */
    }
  }
  
  &.today.highlight {
    animation: todayHighlight 1s ease-in-out;
  }
  
  &.selected {
    background: var(--primary-color);
    overflow: hidden;
    color: white;
  }
  
  &.selected .task-title{
    color: white;
  }
}

.date-number {
  font-weight: 600;
  margin-bottom: 4px;
}

.date-tasks {
  display: flex;
  flex-direction: column;
  gap: 2px;
  max-height: 100px;
  overflow-y: auto;
  overflow-x: hidden;
  padding-bottom: 20px;
}

/* 周视图样式 */
.week-view {
  height: 100%;
  display: flex;
  flex-direction: column;
}

.week-header {
  display: grid;
  grid-template-columns: 60px repeat(7, 1fr);
  border-bottom: 1px solid var(--border-color);
  background: var(--surface-color);
}

.time-column {
  border-right: 1px solid var(--border-color);
}

.day-header {
  padding: 12px;
  text-align: center;
  border-right: 1px solid var(--border-color);
  
  &.today {
    background: rgba(var(--primary-color), 0.1);
  }
}

.day-name {
  font-size: 12px;
  color: #6b7280;
  margin-bottom: 4px;
}

.day-number {
  font-weight: 600;
  font-size: 16px;
}

.week-body {
  flex: 1;
  display: grid;
  grid-template-columns: 60px repeat(7, 1fr);
  overflow-y: auto;
  min-height: 0;
  height: 100%;
}

.time-slots {
  border-right: 1px solid var(--border-color);
}

.time-slot {
  height: 60px;
  border-bottom: 1px solid var(--border-color);
  display: flex;
  align-items: flex-start;
  padding: 4px 8px;
}

.day-cell {
  border-right: 1px solid var(--border-color);
  border-bottom: 1px solid var(--border-color);
  position: relative;
  min-height: 60px;
  
  &:hover {
    background: var(--button-secondary-hover);
  }
}

.time-label {
  font-size: 12px;
  color: var(--text-secondary);
}

.week-days {
  display: contents;
}

.day-column {
  border-right: 1px solid var(--border-color);
}

.hour-slot {
  height: 60px;
  min-height: 60px;
  max-height: 80px;
  border-bottom: 1px solid var(--border-color);
  padding: 2px;
  position: relative;
  max-width: 163px;
  min-width: 163px;
  overflow: auto;
  box-sizing: border-box;
}

/* 日视图样式 */
.day-view {
  height: 100%;
  display: flex;
  flex-direction: column;
}

.day-header {
  padding: 16px 24px;
  border-bottom: 1px solid var(--border-color);
  background: var(--surface-color);
}

.day-header h3 {
  margin: 0;
  font-size: 18px;
  font-weight: 600;
}

.day-body {
  flex: 1;
  overflow-y: auto;
  min-height: 0;
  height: 100%;
}

.day-timeline {
  display: flex;
  height: 100%;
  min-height: 1440px; /* 24小时 * 60px */
}

.time-column {
  width: 80px;
  flex-shrink: 0;
  border-right: 1px solid var(--border-color);
  background: var(--surface-color);
}

.time-column .time-slot {
  height: 60px;
  display: flex;
  align-items: flex-start;
  padding: 4px 8px;
  border-bottom: 1px solid var(--border-color);
}

.time-column .time-label {
  font-size: 12px;
  color: var(--text-secondary);
  font-weight: 500;
}

.tasks-column {
  flex: 1;
  position: relative;
  background: var(--background-color);
}

.hour-grid {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  pointer-events: none;
}

.hour-line {
  height: 60px;
  border-bottom: 1px solid var(--border-color);
  opacity: 0.3;
}

.tasks-container {
  position: relative;
  height: 100%;
  padding: 0 8px;
}

.task-block {
  position: absolute;
  border-radius: 6px;
  cursor: pointer;
  transition: all 0.2s;
  padding: 8px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
  display: flex;
  flex-direction: row;
  align-items: flex-start;
  max-width: 175px;
  height: auto;
  min-height: 45px;
  gap: 4px;
  
  &:hover {
    transform: translateY(-1px);
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15);
  }
  
  &.completed {
    opacity: 0.6;
    
    .task-title {
      text-decoration: line-through;
    }
  }
  
  &.default-task {
    background-color: #6b728040 !important;
    border-left: 4px solid #6b7280 !important;
  }
  
  &.list-task {
    /* 背景色由getTaskBlockStyle动态设置 */
  }
}

.task-block .task-checkbox {
  display: flex;
  align-items: center;
  margin-bottom: 2px;
}

.task-block .task-checkbox input {
  margin: 0;
  width: 14px;
  height: 14px;
}

.task-content {
  flex: 1;
}

.task-block .task-title {
  font-size: 14px;
  font-weight: 500;
  color: var(--text-primary);
  line-height: 1.3;
  margin-bottom: 2px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  max-width: 135px;
  width: 100%;
}

.task-notes {
  font-size: 12px;
  color: var(--text-secondary);
  opacity: 0.8;
  font-weight: 400;
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 3;
  -webkit-box-orient: vertical;
}

.task-block .task-time {
  font-size: 11px;
  color: var(--text-secondary);
  opacity: 0.8;
  font-weight: 400;
}

/* 任务项样式 */
.task-item {
  display: flex;
  align-items: center;
  gap: 6px;
  padding: 4px 6px;
  background: var(--primary-color);
  color: white;
  border-radius: 4px;
  font-size: 12px;
  cursor: pointer;
  margin-bottom: 2px;
  transition: all 0.2s;
  min-width: 0;
  max-width: 100%;
  box-sizing: border-box;
  position: relative;
  z-index: 10; /* 确保任务项目在其他元素之上 */
  
  &:hover {
    background: var(--primary-hover);
  }
  
  &.completed {
    background: var(--text-secondary);
    text-decoration: line-through;
  }
}

.task-checkbox {
  display: flex;
  align-items: center;
}

.task-checkbox input {
  margin: 0;
  width: 12px;
  height: 12px;
}

.task-title {
  flex: 1;
  overflow: hidden;
  color: var(--text-primary);
  text-overflow: ellipsis;
  white-space: nowrap;
}

.task-time {
  font-size: 10px;
  color: var(--text-secondary);
  opacity: 0.8;
}

/* 任务编辑弹窗样式 */
.task-edit-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
}

.task-edit-modal {
  background: white;
  border-radius: 8px;
  width: 500px;
  max-width: 90vw;
  max-height: 80vh;
  overflow: hidden;
  display: flex;
  flex-direction: column;
}

.modal-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px 24px;
  border-bottom: 1px solid #e5e7eb;
}

.modal-header h3 {
  margin: 0;
  font-size: 18px;
  font-weight: 600;
}

.close-btn {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 32px;
  height: 32px;
  border: none;
  background: none;
  cursor: pointer;
  border-radius: 4px;
  transition: background-color 0.2s;
  
  &:hover {
    background: #f3f4f6;
  }
}

.modal-body {
  padding: 24px;
  overflow-y: auto;
}

.form-group {
  margin-bottom: 16px;
}

.form-row {
  display: flex;
  gap: 16px;
  margin-bottom: 16px;
}

.form-row .form-group {
  flex: 1;
  margin-bottom: 0;
}

.form-group label {
  display: block;
  margin-bottom: 6px;
  font-weight: 500;
  color: #374151;
}

.form-input,
.form-select,
.form-textarea {
  width: 100%;
  padding: 8px 12px;
  border: 1px solid #d1d5db;
  border-radius: 6px;
  font-size: 14px;
  transition: border-color 0.2s;
  
  &:focus {
    outline: none;
    border-color: #3b82f6;
    box-shadow: 0 0 0 3px rgba(59, 130, 246, 0.1);
  }
}

.form-textarea {
  resize: vertical;
  min-height: 80px;
}

.modal-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
  padding: 16px 24px;
  border-top: 1px solid #e5e7eb;
}

.btn {
  padding: 8px 16px;
  border-radius: 6px;
  font-size: 14px;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.2s;
  border: 1px solid transparent;
}

.btn-secondary {
  background: white;
  color: #374151;
  border-color: #d1d5db;
  
  &:hover {
    background: #f3f4f6;
  }
}

.btn-primary {
  background: #3b82f6;
  color: white;
  
  &:hover {
    background: #2563eb;
  }
}

/* 动画定义 */
@keyframes todayPulse {
  0%, 100% {
    opacity: 0;
    transform: scale(1);
  }
  50% {
    opacity: 0.3;
    transform: scale(1.02);
  }
}

@keyframes todayHighlight {
  0% {
    transform: scale(1);
    box-shadow: 0 0 0 0 rgba(var(--primary-color), 0.7);
  }
  50% {
    transform: scale(1.05);
    box-shadow: 0 0 0 10px rgba(var(--primary-color), 0.3);
  }
  100% {
    transform: scale(1);
    box-shadow: 0 0 0 0 rgba(var(--primary-color), 0);
  }
}

/* 重复任务时间错误模态框样式 */
.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
}

.repeat-task-error-modal {
  background: white;
  border-radius: 12px;
  box-shadow: 0 20px 25px -5px rgba(0, 0, 0, 0.1), 0 10px 10px -5px rgba(0, 0, 0, 0.04);
  max-width: 500px;
  width: 90%;
  max-height: 80vh;
  overflow: hidden;
  animation: modalSlideIn 0.3s ease-out;
}

@keyframes modalSlideIn {
  from {
    opacity: 0;
    transform: translateY(-20px) scale(0.95);
  }
  to {
    opacity: 1;
    transform: translateY(0) scale(1);
  }
}

.repeat-task-error-modal .modal-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 20px 24px;
  border-bottom: 1px solid #e5e7eb;
  background: #fefefe;
}

.repeat-task-error-modal .modal-title {
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 18px;
  font-weight: 600;
  color: #111827;
}

.repeat-task-error-modal .warning-icon {
  flex-shrink: 0;
}

.repeat-task-error-modal .close-btn {
  background: none;
  border: none;
  padding: 4px;
  cursor: pointer;
  border-radius: 4px;
  color: #6b7280;
  transition: all 0.2s;
}

.repeat-task-error-modal .close-btn:hover {
  background: #f3f4f6;
  color: #374151;
}

.repeat-task-error-modal .modal-content {
  padding: 24px;
}

.repeat-task-error-modal .error-info {
  text-align: left;
}

.repeat-task-error-modal .error-message {
  font-size: 16px;
  color: #dc2626;
  font-weight: 500;
  margin-bottom: 16px;
  line-height: 1.5;
}

.repeat-task-error-modal .task-info {
  background: #fef2f2;
  border: 1px solid #fecaca;
  border-radius: 8px;
  padding: 16px;
  margin: 16px 0;
}

.repeat-task-error-modal .task-info p {
  margin: 0 0 8px 0;
  font-size: 14px;
  color: #374151;
  line-height: 1.4;
}

.repeat-task-error-modal .task-info p:last-child {
  margin-bottom: 0;
}

.repeat-task-error-modal .task-info strong {
  color: #dc2626;
  font-weight: 600;
}

.repeat-task-error-modal .error-submessage {
  font-size: 14px;
  color: #6b7280;
  line-height: 1.5;
  margin-top: 12px;
}

.repeat-task-error-modal .modal-actions {
  padding: 16px 24px;
  border-top: 1px solid #e5e7eb;
  background: #fafafa;
  display: flex;
  justify-content: flex-end;
}

.repeat-task-error-modal .confirm-btn {
  background: #3b82f6;
  color: white;
  border: none;
  padding: 10px 20px;
  border-radius: 6px;
  font-size: 14px;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.2s;
}

.repeat-task-error-modal .confirm-btn:hover {
  background: #2563eb;
  transform: translateY(-1px);
  box-shadow: 0 4px 8px rgba(59, 130, 246, 0.3);
}

.repeat-task-error-modal .confirm-btn:active {
  transform: translateY(0);
  box-shadow: 0 2px 4px rgba(59, 130, 246, 0.3);
}
</style>